<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="styles.css">
    <title>图片预处理系统</title>
    <meta charset="UTF-8">
    <!-- 添加 Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
    <style>
        /* 添加新的样式 */
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #34495e;
            --accent-color: #2ecc71;
            --background-color: #f5f6fa;
            --sidebar-bg: #2c3e50;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background: var(--background-color);
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            background: var(--sidebar-bg);
            width: 280px;
            padding: 20px;
            color: white;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }

        .logo {
            font-size: 24px;
            font-weight: 600;
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            margin-bottom: 20px;
        }

        .nav-group {
            margin-bottom: 15px;
        }

        .nav-header {
            padding: 12px;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .nav-header:hover {
            background: rgba(255,255,255,0.1);
        }

        .nav-item {
            padding: 12px 20px;
            margin: 5px 0;
            cursor: pointer;
            border-radius: 8px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .nav-item:hover {
            background: rgba(74, 144, 226, 0.2);
            transform: translateX(5px);
        }

        .nav-item.active {
            background: var(--primary-color);
            color: white;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            padding: 30px;
            background: white;
            border-radius: 20px;
            margin: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }

        /* 上传区域样式 */
        .upload-area {
            border: 2px dashed var(--primary-color);
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            background: rgba(74, 144, 226, 0.05);
        }

        .upload-area:hover {
            border-color: var(--accent-color);
            background: rgba(46, 204, 113, 0.05);
        }

        .upload-content i {
            font-size: 48px;
            color: var(--primary-color);
            margin-bottom: 15px;
        }

        /* 预览区域样式 */
        .preview-area {
            margin-top: 20px;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            position: relative;
        }

        #preview {
            max-width: 100%;
            height: auto;
            display: block;
        }

        /* 操作按钮样式 */
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            background: var(--primary-color);
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(74, 144, 226, 0.3);
        }

        /* 加载动画 */
        #loading {
            display: none;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0,0,0,0.7);
            color: white;
            padding: 15px 30px;
            border-radius: 20px;
            z-index: 100;
        }

        /* 工具控制面板样式 */
        .operation-box {
            margin-top: 20px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .resize-container {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .resize-field {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        input[type="number"] {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            width: 100px;
        }

        /* 添加过渡动画 */
        .nav-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
        }

        .nav-content.show {
            max-height: 500px;
        }

        .tool-container {
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .batch-options {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 10px;
            margin-bottom: 15px;
        }

        .batch-options label {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px;
            border-radius: 4px;
            background: #f5f6fa;
            cursor: pointer;
        }

        .crop-controls {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-bottom: 15px;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            justify-content: center;
        }

        .save-btn {
            background: var(--accent-color);
        }

        .restore-btn {
            background: var(--secondary-color);
        }

        .content-layout {
            display: flex;
            gap: 20px;
            height: 100%;
        }

        .preview-section {
            flex: 1;
            min-width: 0; /* 防止溢出 */
        }

        .operation-section {
            width: 300px;
            min-width: 300px;
        }

        .tool-group {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .tool-group h4 {
            margin: 0 0 10px 0;
            color: var(--secondary-color);
        }

        .basic-tools {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .rotate-container,
        .flip-container {
            display: flex;
            gap: 10px;
        }

        /* 修改预览区域样式 */
        .preview-area {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .preview-area img {
            max-width: 100%;
            height: auto;
            border-radius: 8px;
        }

        /* 修改上传区域样式 */
        .upload-area {
            height: 300px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .upload-preview-container {
            display: flex;
            flex-direction: column;
            gap: 20px;
            margin-bottom: 20px;
        }

        .operation-box {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        /* 移除之前的 content-layout 相关样式 */
        .content-layout,
        .preview-section,
        .operation-section {
            display: block;
            width: 100%;
        }

        .upload-new-btn {
            background: var(--primary-color);
        }

        .preview-area.hidden {
            display: none;
        }

        .upload-area.hidden {
            display: none;
        }

        .image-container {
            background: white;
            padding: 20px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .upload-preview-area {
            position: relative;
            min-height: 300px;
            border: 2px dashed var(--primary-color);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            transition: all 0.3s ease;
        }

        .upload-preview-area:hover {
            border-color: var(--accent-color);
            background: rgba(46, 204, 113, 0.05);
        }

        .upload-preview-area img {
            max-width: 100%;
            max-height: 500px;
            object-fit: contain;
        }

        .upload-content {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            z-index: 1;
            pointer-events: none;
        }

        .upload-preview-area.has-image .upload-content {
            display: none;
        }

        .slider-container {
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 10px 0;
        }

        .slider-container input[type="range"] {
            flex: 1;
        }

        .value-display {
            min-width: 40px;
            text-align: right;
        }

        /* 表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            overflow: hidden;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: center;
        }

        th {
            background-color: #4CAF50;
            color: white;
            font-weight: bold;
        }

        tr:hover {
            background-color: #f1f1f1;
            cursor: pointer;
        }

        /* 按钮样式 */
        button {
            background-color: #4CAF50; /* 绿色 */
            color: white;
            border: none;
            padding: 10px 15px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            margin: 4px 2px;
            transition: background-color 0.3s, transform 0.3s;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049; /* 深绿色 */
            transform: scale(1.05);
        }

        /* 模态框样式 */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal img {
            max-width: 90%;
            max-height: 90%;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
        }

        .modal button {
            position: absolute;
            top: 20px;
            right: 20px;
            background: red;
            color: white;
            border: none;
            padding: 10px;
            cursor: pointer;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .modal button:hover {
            background: darkred;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧导航栏 -->
        <div class="sidebar">
            <div class="logo">图片预处理系统</div>
            
            <!-- 基础调整模块 -->
            <div class="nav-group">
                <div class="nav-header" onclick="toggleNavGroup(this)">
                    <span>基础调整</span>
                    <span class="arrow">▼</span>
                </div>
                <div class="nav-content">
                    <div class="nav-item" onclick="showTool('resize')">
                        <i class="fas fa-expand"></i>调整大小
                    </div>
                    <div class="nav-item" onclick="showTool('rotate')">
                        <i class="fas fa-sync"></i>旋转
                    </div>
                    <div class="nav-item" onclick="showTool('flip')">
                        <i class="fas fa-exchange-alt"></i>翻转
                    </div>
                    <div class="nav-item" onclick="showTool('crop')">
                        <i class="fas fa-crop"></i>裁剪
                    </div>
                </div>
            </div>

            <!-- 图片处理模块 -->
            <div class="nav-group">
                <div class="nav-header" onclick="toggleNavGroup(this)">
                    <span>图片处理</span>
                    <span class="arrow">▼</span>
                </div>
                <div class="nav-content">
                    <div class="nav-item" onclick="showTool('brightness')">
                        <i class="fas fa-sun"></i>亮度
                    </div>
                    <div class="nav-item" onclick="showTool('contrast')">
                        <i class="fas fa-adjust"></i>对比度
                    </div>
                    <div class="nav-item" onclick="showTool('sharpen')">
                        <i class="fas fa-vector-square"></i>锐化
                    </div>
                    <div class="nav-item" onclick="showTool('blur')">
                        <i class="fas fa-cloud"></i>模糊
                    </div>
                    <div class="nav-item" onclick="showTool('grayscale')">
                        <i class="fas fa-gray"></i>灰度化
                    </div>
                    <div class="nav-item" onclick="showTool('equalize')">
                        <i class="fas fa-balance-scale"></i>直方图均衡化
                    </div>
                </div>
            </div>
            <!-- 添加操作历史记录的导航组 -->
            <div class="nav-group">
                <div class="nav-header" onclick="toggleNavGroup(this)">
                    <span>操作历史</span>
                    <span class="arrow">▼</span>
                </div>
                <div class="nav-content">
                    <div class="nav-item" onclick="showHistory()">
                        <i class="fas fa-history"></i>查看历史记录
                    </div>
                </div>
            </div>
            <!-- 添加批处理模块 -->
        </div>

        <!-- 主内容区 -->
        <div class="main-content">
            <!-- 上传和预览区域 -->
            <div class="upload-preview-container">
                <div class="image-container">
                    <!-- 上传区域和预览区域合并 -->
                    <div class="upload-preview-area" id="uploadPreviewArea" >
                        <input type="file" id="fileInput" accept="image/*" style="display: none" onchange="handleFileSelect(event)">
                        <!-- 无图片时显示上传提示 -->
                        <div class="upload-content" onclick="document.getElementById('fileInput').click()">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p class="upload-text">点击或拖拽图片到此处</p>
                            <p class="upload-hint">支持 JPG、PNG 格式</p>
                        </div>
                        <!-- 预览图片 -->
                        <img id="preview" src="" alt="预览" style="display: none;">
                        <div id="loading">处理中...</div>
                    </div>
                    <!-- 操作按钮 -->
                    <div class="action-buttons" style="display: none;">
                        <button class="btn save-btn" onclick="saveImage()">
                            <i class="fas fa-download"></i> 保存图片
                        </button>
                        <button class="btn restore-btn" onclick="restoreOriginal()">
                            <i class="fas fa-undo"></i> 还原原图
                        </button>
                        <button class="btn upload-new-btn" onclick="resetUpload()">
                            <i class="fas fa-upload"></i> 上传新图片
                        </button>
                    </div>
                </div>
            </div>
            <!-- 操作方框 -->
            <div class="operation-box">
                <!-- 操作按钮会根据选择的工具动态显示在这里 -->
            </div>
        </div>
    </div>

    <script>
        //选着文件夹
        function handleFileSelect(event) {
            const file = event.target.files[0];
            if (file) {
                console.log("文件已选择:", file.name);
                document.getElementById('loading').style.display = 'block';
                
                const reader = new FileReader();
                reader.onload = function (e) {
                    originalImage = e.target.result;
                    const previewImage = document.getElementById('preview');
                    previewImage.src = originalImage;
                    previewImage.style.display = 'block';
                    
                    // 显示操作按钮
                    document.querySelector('.action-buttons').style.display = 'flex';
                    // 添加has-image类
                    document.querySelector('.upload-preview-area').classList.add('has-image');
                    
                    setTimeout(() => {
                        document.getElementById('loading').style.display = 'none';
                    }, 500);
                };
                reader.readAsDataURL(file);
                event.target.value = '';
            }
        }
        // 监听上传区域的点击
        document.getElementById('uploadPreviewArea').addEventListener('click', function () {
           document.getElementById('fileInput').click();
        });

        // 重置上传区域
        function resetUpload() {
            const previewImage = document.getElementById('preview');
            previewImage.style.display = 'none';
            previewImage.src = '';
            
            // 隐藏操作按钮
            document.querySelector('.action-buttons').style.display = 'none';
            // 移除has-image类
            document.querySelector('.upload-preview-area').classList.remove('has-image');
            // 清除原始图片
            originalImage = null;
            // 清除操作区域
            document.querySelector('.operation-box').innerHTML = '';
        }


        // 修改拖拽上传功能
        document.addEventListener('DOMContentLoaded', () => {
            const dropZone = document.querySelector('.upload-preview-area');
            
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                dropZone.addEventListener(eventName, preventDefaults, false);
            });

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            dropZone.addEventListener('drop', (e) => {
                const file = e.dataTransfer.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        originalImage = e.target.result;
                        const previewImage = document.getElementById('preview');
                        previewImage.src = originalImage;
                        previewImage.style.display = 'block';
                        
                        document.querySelector('.action-buttons').style.display = 'flex';
                        document.querySelector('.upload-preview-area').classList.add('has-image');
                    };
                    reader.readAsDataURL(file);
                }
            });
        });

        // 修改显示工具函数
        function showTool(toolName) {
            // 显示上传和预览区域
            document.querySelector('.upload-preview-container').style.display = 'flex';
            
            // 移除所有工具项的活动状态
            document.querySelectorAll('.nav-item').forEach(item => {
                item.classList.remove('active');
            });
            
            // 设置当前工具项的活动状态
            event.currentTarget.classList.add('active');

            // 清除现有的操作界面
            const operationBox = document.querySelector('.operation-box');
            operationBox.innerHTML = '';

            // 根据选择的工具显示对应的操作界面
            switch(toolName) {
                case 'resize':
                    showResizeUI();
                    break;
                case 'rotate':
                    showRotateUI();
                    break;
                case 'flip':
                    showFlipUI();
                    break;
                case 'crop':
                    showCropUI();
                    break;
                case 'brightness':
                    showBrightnessUI();
                    break;
                case 'contrast':
                    showContrastUI();
                    break;
                case 'grayscale':
                    handleEffect('grayscale');
                    break;
                case 'sharpen':
                    handleEffect('sharpen');
                    break;
                case 'blur':
                    handleEffect('blur');
                    break;
                case 'equalize':
                    handleEffect('equalize');
                    break;
                // ... 其他工具的处理
            }
        }

        // 显示调整大小的UI
        function showResizeUI() {
            const resizeContainer = document.createElement('div');
            resizeContainer.innerHTML = `
                <div class="tool-container">
                    <h4>调整大小</h4>
                    <div class="resize-container">
                        <div class="resize-field">
                            <label for="resizeWidth">宽度:</label>
                            <input type="number" id="resizeWidth" value="200" min="1">
                        </div>
                        <div class="resize-field">
                            <label for="resizeHeight">高度:</label>
                            <input type="number" id="resizeHeight" value="300" min="1">
                        </div>
                        <button class="btn btn-primary" onclick="resizeImage()">调整大小</button>
                    </div>
                </div>
            `;
            document.querySelector('.operation-box').appendChild(resizeContainer);
        }

        // 显示旋转的UI
        function showRotateUI() {
            const rotateContainer = document.createElement('div');
            rotateContainer.innerHTML = `
                <div class="tool-container">
                    <h4>旋转</h4>
                    <div class="rotate-container">
                        <button class="btn" onclick="rotateImage('right')">向左旋转</button>
                        <button class="btn" onclick="rotateImage('left')">向右旋转</button> 
                    </div>
                </div>
            `;
            document.querySelector('.operation-box').appendChild(rotateContainer);
        }

        // 显示翻转的UI
        function showFlipUI() {
            const flipContainer = document.createElement('div');
            flipContainer.innerHTML = `
                <div class="tool-container">
                    <h4>翻转</h4>
                    <div class="flip-container">
                        <button class="btn" onclick="flipImage('horizontal')">水平翻转</button>
                        <button class="btn" onclick="flipImage('vertical')">垂直翻转</button>
                    </div>
                </div>
            `;
            document.querySelector('.operation-box').appendChild(flipContainer);
        }

        // 处理功能选择
        function toggleNavGroup(header) {
            const content = header.nextElementSibling;
            const arrow = header.querySelector('.arrow');
            // 切换当前组的显示状态
            header.classList.toggle('active');
            content.classList.toggle('show');
            // 关闭其他已打开的组
            const allContents = document.querySelectorAll('.nav-content');
            const allHeaders = document.querySelectorAll('.nav-header');
            allContents.forEach((item) => {
                if (item !== content) {
                    item.classList.remove('show');
                }
            });
            allHeaders.forEach((item) => {
                if (item !== header) {
                    item.classList.remove('active');
                }
            });
        }

        // 调整图片大小
        function resizeImage() {
            const width = document.getElementById('resizeWidth').value;
            const height = document.getElementById('resizeHeight').value;
            const imageElement = document.getElementById('preview');
            const imageSrc = imageElement.src;

            // 处理 blob: URL（如果存在）
            if (imageSrc.startsWith('blob:')) {
                fetch(imageSrc)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = function () {
                            sendResizeRequest(reader.result, width, height);
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => console.error('读取图片失败:', error));
            } else {
                sendResizeRequest(imageSrc, width, height);
            }
        }
        function sendResizeRequest(imageData, width, height) {
            fetch('/resize', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    image: imageData,
                    width: parseInt(width),
                    height: parseInt(height)
                })
            })
            .then(response => response.blob())
            .then(blob => {
                // 更新预览图
                const newImgUrl = URL.createObjectURL(blob);
                document.getElementById('preview').src = newImgUrl;
            })
            .catch(error => {
                alert('调整大小失败: ' + error.message);
            });
        }


        //旋转函数
        function rotateImage(direction) {
            const angle = direction === 'left' ? -90 : 90;
            const imageElement = document.getElementById('preview');
            const imageSrc = imageElement.src;
        
            // 如果是 blob URL，需要转换为 Base64
            if (imageSrc.startsWith('blob:')) {
                fetch(imageSrc)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = function () {
                            sendImageToBackend(reader.result, angle);
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => console.error('读取图片失败:', error));
            } else {
                sendImageToBackend(imageSrc, angle);
            }
        }
        function sendImageToBackend(imageData, angle) {
            fetch('/rotate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    image: imageData, // 发送 Base64
                    angle: angle
                })
            })
            .then(response => response.blob())
            .then(blob => {
                const newImgUrl = URL.createObjectURL(blob);
                document.getElementById('preview').src = newImgUrl;
            })
            .catch(error => {
                alert('旋转失败: ' + error.message);
            });
        }

        // 翻转函数
        function flipImage(direction) {
            const imageElement = document.getElementById('preview');
            const imageSrc = imageElement.src;

            // 处理 blob: URL（如果存在）
            if (imageSrc.startsWith('blob:')) {
                fetch(imageSrc)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = function () {
                            sendFlipRequest(reader.result, direction);
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => console.error('读取图片失败:', error));
            } else {
                sendFlipRequest(imageSrc, direction);
            }
        }
        function sendFlipRequest(imageData, direction) {
            fetch('/api/flip', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    image: imageData,
                    direction: direction
                })
            })
            .then(response => response.blob())
            .then(blob => {
                const newImgUrl = URL.createObjectURL(blob);
                document.getElementById('preview').src = newImgUrl;
            })
            .catch(error => console.error('翻转失败:', error));
        }


        //裁剪函数
        function cropImage() {
            const imageElement = document.getElementById('preview');
            const imageSrc = imageElement.src;
            // 处理 blob: URL（如果存在）
            if (imageSrc.startsWith('blob:')) {
                fetch(imageSrc)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = function () {
                            sendCropRequest(reader.result);
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => console.error('读取图片失败:', error));
            } else {
                sendCropRequest(imageSrc);
            }
        }
        function sendCropRequest(imageData) {
            const x = document.getElementById('cropX').value;
            const y = document.getElementById('cropY').value;
            const width = document.getElementById('cropWidth').value;
            const height = document.getElementById('cropHeight').value;
        
            fetch('/api/crop', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    image: imageData,
                    x: parseInt(x),
                    y: parseInt(y),
                    width: parseInt(width),
                    height: parseInt(height)
                })
            })
            .then(response => response.blob())
            .then(blob => {
                const newImgUrl = URL.createObjectURL(blob);
                document.getElementById('preview').src = newImgUrl;
            })
            .catch(error => console.error('裁剪失败:', error));
        }
        
        // 修改亮度和对比度的处理函数
        function handleBrightness(value) {
            const valueDisplay = document.querySelector('.slider-container .value-display');
            valueDisplay.textContent = value;
            handleEffect('brightness', { factor: parseFloat(value) });
        }

        function handleContrast(value) {
            const valueDisplay = document.querySelector('.slider-container .value-display');
            valueDisplay.textContent = value;
            handleEffect('contrast', { factor: parseFloat(value) });
        }

        
        function applyBatchProcessing() {
            const image = document.getElementById('preview').src;
            const selectedOptions = Array.from(document.querySelectorAll('.batch-options input:checked'))
                .map(input => input.value);

            fetch('/api/batch', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    image: image,
                    operations: selectedOptions
                })
            })
            .then(response => response.blob())
            .then(blob => {
                const newImgUrl = URL.createObjectURL(blob);
                document.getElementById('preview').src = newImgUrl;
            });
        }

        // 保存原始图片
        let originalImage = null;

        // 处理图片效果
        function handleEffect(effectType, params = {}) {
            const imageElement = document.getElementById('preview');
            const currentImage = imageElement.src;
            if (!currentImage || currentImage === '') {
                alert('请先上传图片');
                return;
            }
            document.getElementById('loading').style.display = 'block';
            // 处理 blob: URL（如果存在）
            if (currentImage.startsWith('blob:')) {
                fetch(currentImage)
                    .then(response => response.blob())
                    .then(blob => {
                        const reader = new FileReader();
                        reader.onloadend = function () {
                            sendEffectRequest(reader.result, effectType, params);
                        };
                        reader.readAsDataURL(blob);
                    })
                    .catch(error => {
                        alert('读取图片失败: ' + error.message);
                        document.getElementById('loading').style.display = 'none';
                    });
            } else {
                sendEffectRequest(currentImage, effectType, params);
            }
        }

        function sendEffectRequest(imageData, effectType, params) {
            fetch(`/api/${effectType}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    image: imageData,
                    ...params
                })
            })
            .then(response => response.blob())
            .then(blob => {
                const newImgUrl = URL.createObjectURL(blob);
                document.getElementById('preview').src = newImgUrl;
            })
            .catch(error => {
                alert(`${effectType}处理失败: ${error.message}`);
            })
            .finally(() => {
                document.getElementById('loading').style.display = 'none';
            });
        }


        // 显示亮度UI
        function showBrightnessUI() {
            const brightnessContainer = document.createElement('div');
            brightnessContainer.innerHTML = `
                <div class="tool-container">
                    <h4>调整亮度</h4>
                    <div class="slider-container">
                        <input type="range" min="0" max="2" step="0.1" value="1" 
                               oninput="handleBrightness(this.value)">
                        <span class="value-display">1.0</span>
                    </div>
                </div>
            `;
            document.querySelector('.operation-box').appendChild(brightnessContainer);
        }

        // 显示对比度UI
        function showContrastUI() {
            const contrastContainer = document.createElement('div');
            contrastContainer.innerHTML = `
                <div class="tool-container">
                    <h4>调整对比度</h4>
                    <div class="slider-container">
                        <input type="range" min="0" max="2" step="0.1" value="1" 
                               oninput="handleContrast(this.value)">
                        <span class="value-display">1.0</span>
                    </div>
                </div>
            `;
            document.querySelector('.operation-box').appendChild(contrastContainer);
        }

        // 在操作方框中添加裁剪功能的UI
        function showCropUI() {
            const cropContainer = document.createElement('div');
            cropContainer.innerHTML = `
                <div class="tool-container">
                    <h4>裁剪</h4>
                    <div class="resize-container">
                        <div class="resize-field">
                            <label for="cropX">X:</label>
                            <input type="number" id="cropX" value="0" min="0">
                        </div>
                        <div class="resize-field">
                            <label for="cropY">Y:</label>
                            <input type="number" id="cropY" value="0" min="0">
                        </div>
                        <div class="resize-field">
                            <label for="cropWidth">宽度:</label>
                            <input type="number" id="cropWidth" value="100" min="1">
                        </div>
                        <div class="resize-field">
                            <label for="cropHeight">高度:</label>
                            <input type="number" id="cropHeight" value="100" min="1">
                        </div>
                        <button class="btn" onclick="cropImage()">裁剪</button>
                    </div>
                </div>
            `;
            document.querySelector('.operation-box').appendChild(cropContainer);
        }

        // 保存图片的功能
        function saveImage() {
            const imageSrc = document.getElementById('preview').src;  // 获取当前图片的src
            if (!imageSrc) {
                alert('请先上传图片');
                return;
            }
            // 创建一个 canvas 元素
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();
            img.src = imageSrc;

            img.onload = function() {
                // 设置 canvas 尺寸为图片的尺寸
                canvas.width = img.width;
                canvas.height = img.height;

                // 将图片绘制到 canvas 上
                ctx.drawImage(img, 0, 0);

                // 获取图片的 base64 编码
                const dataURL = canvas.toDataURL('image/png'); // 可以选择 'image/jpeg' 格式

                // 创建下载链接
                const link = document.createElement('a');
                link.href = dataURL; // 设置下载链接
                link.download = 'downloaded_image.png'; // 设置下载的文件名

                // 触发点击事件来下载文件
                link.click();
            };
        }

        // 还原原图的功能
        function restoreOriginal() {
            if (originalImage) {
                document.getElementById('preview').src = originalImage;
            } else {
                alert('没有原始图片可还原');
            }
        }

        function showHistory() {
            // 隐藏上传和预览区域
            document.querySelector('.upload-preview-container').style.display = 'none';
            const imageSrc = document.getElementById('preview').src;
            fetch('/api/history')
                .then(response => response.json())
                .then(history => {
                    // 处理并显示历史记录
                    const historyContainer = document.createElement('div');
                    historyContainer.innerHTML = '<h4>操作历史记录</h4>';

                    // 创建表格
                    const table = document.createElement('table');
                    table.style.width = '100%';
                    table.style.borderCollapse = 'collapse';
                    table.innerHTML = `
                        <tr>
                            <th style="border: 1px solid #ddd; padding: 8px;">原图片</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">详细操作</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">处理后的图片</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">操作</th>
                            <th style="border: 1px solid #ddd; padding: 8px;">时间</th>
                        </tr>
                    `;

                    history.forEach((item, index) => {
                        const row = document.createElement('tr');
                        row.style.border = '1px solid #ddd';

                        row.innerHTML = `
                            <td style="border: 1px solid #ddd; padding: 8px;">
                                <img src="${originalImage}" alt="原图片" style="max-width: 100px; cursor: pointer;" onclick="showImage('${originalImage}')">
                            </td>
                            <td style="border: 1px solid #ddd; padding: 8px;">${item.operation} - ${item.details}</td>
                            <td style="border: 1px solid #ddd; padding: 8px;">
                                <img src="${imageSrc}" alt="处理后的图片" style="max-width: 100px; cursor: pointer;" onclick="showImage('${imageSrc}')">
                            </td>
                            <td style="border: 1px solid #ddd; padding: 8px;">
                                <button onclick="downloadImage('${imageSrc}')">下载</button>
                                <button onclick="deleteImage(${index})">删除</button>
                            </td>
                            <td style="border: 1px solid #ddd; padding: 8px;">${item.time}</td>
                        `;
                        table.appendChild(row);
                    });

                    historyContainer.appendChild(table);
                    document.querySelector('.operation-box').innerHTML = '';
                    document.querySelector('.operation-box').appendChild(historyContainer);
                })
                .catch(error => console.error('获取历史记录失败:', error));
        }

        function showImage(imagePath) {
            //显示图片的弹出框
            const imageModal = document.createElement('div');
            imageModal.classList.add('modal');
            imageModal.innerHTML = `
                    <img src="${imagePath}" style="max-width: 100%; max-height: 80vh; display: block; margin: 0 auto;">
                    <button onclick="document.body.removeChild(this.parentNode)">关闭</button>
            `;
            document.body.appendChild(imageModal);
        }

        function downloadImage(imageSrc) {
            // 实现下载功能
             if (!imageSrc) {
                alert('请先上传图片');
                return;
            }
            // 创建一个 canvas 元素
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();
            img.src = imageSrc;

            img.onload = function() {
                // 设置 canvas 尺寸为图片的尺寸
                canvas.width = img.width;
                canvas.height = img.height;

                // 将图片绘制到 canvas 上
                ctx.drawImage(img, 0, 0);

                // 获取图片的 base64 编码
                const dataURL = canvas.toDataURL('image/png'); // 可以选择 'image/jpeg' 格式

                // 创建下载链接
                const link = document.createElement('a');
                link.href = dataURL; // 设置下载链接
                link.download = 'downloaded_image.png'; // 设置下载的文件名

                // 触发点击事件来下载文件
                link.click();
            };
        }

        function deleteImage(index) {
            // 实现删除历史记录功能
            if (confirm(`确定要删除这条历史记录吗?`)) {
                // 发送请求到后端删除历史记录
                fetch(`/api/delete_history?index=${index}`, { method: 'DELETE' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('历史记录已删除');
                            showHistory(); // 刷新历史记录
                        } else {
                            alert('删除失败: ' + data.error);
                        }
                    })
                    .catch(error => alert('删除请求失败: ' + error));
            }
        }

    </script>
    
    <!-- 添加 Font Awesome 图标 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">

    <style>
    footer {
    text-align: center; /* 文字居中 */
    padding: 10px;
    background-color: #f1f1f1; /* 灰色背景 */
    color: #666; /* 灰色文字 */
    font-size: 14px;
    }
            
    footer a {
    color: #666;
    text-decoration: none;
    }
            
    footer a:hover {
    text-decoration: underline;
    }
    </style>
    <footer>
    <p>北京紫晴科技有限公司版权所有 &copy; </p >
    <p>备案号：<a href="https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=%E5%8C%97%E4%BA%AC%E7%B4%AB%E6%99%B4%E7%A7%91%E6%8A%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&fenlei=256&oq=%25E5%258C%2597%25E4%25BA%25AC%25E7%25B4%25AB%25E6%2599%25B4%25E7%25A7%2591%25E6%258A%2580%25E6%259C%2589%25E9%2599%2590%25E5%2585%25AC%25E5%258F%25B8&rsv_pq=e4c0a2a900010c00&rsv_t=8318qE1Quqve4nRjKWb9ZZzQK74DjCW7ivXjxC4ID9yV%2BU3qi1PD9t0J%2BHY&rqlang=cn&rsv_dl=tb&rsv_enter=0&rsv_btype=t&inputT=146413&rsv_sug3=4&rsv_sug1=4&rsv_sug7=100&rsv_sug4=146913&rsv_sug=1"target="_blank"> 京ICP备*****号-1</a ></p > 
    </footer>

</body>
</html>

